import SockJS from 'sockjs-client';
import { Stomp } from '@stomp/stompjs';
export class StompClient {
	constructor(brokerURL) {
		this.connect = headers => {
			return new Promise((resolve, reject) => {
				this.origin.connect(
					headers,
					frame => {
						resolve({
							frame,
							client: this
						});
					},
					error => {
						reject(error);
					}
				);
			});
		};
		this.disconnect = headers => {
			return new Promise(resolve => {
				this.origin.disconnect(frame => {
					resolve({
						frame,
						client: this
					});
				}, headers);
			});
		};
		this.subscribe = (destination, callback, headers) => {
			const subscription = this.origin.subscribe(
				destination,
				message => {
					callback({
						message,
						subscription
					});
				},
				headers
			);
		};
		this.send = (destination, data, headers) => {
			this.origin.send(destination, headers, JSON.stringify(data));
		};
		if (brokerURL.indexOf('ws') === 0) {
			this.origin = Stomp.client(brokerURL);
		} else {
			this.origin = Stomp.over(new SockJS(brokerURL));
		}
		// eslint-disable-next-line
		this.origin.debug = () => {};
	}
}
